/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package io.renren.common.exception;

import io.renren.common.utils.R;
import io.renren.modules.sys.service.MailService;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;

/**
 * 异常处理器
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2016-10-27
 */
@RestControllerAdvice
public class RRExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private MailService mailService;

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(RRException.class)
	public R handleRRException(RRException e){
		R r = new R();
		r.put("code", e.getCode());
		r.put("msg", e.getMessage());

		return r;
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public R handleDuplicateKeyException(DuplicateKeyException e){
		logger.error(e.getMessage(), e);
		return R.error("数据库中已存在该记录");
	}

	@ExceptionHandler(AuthorizationException.class)
	public R handleAuthorizationException(AuthorizationException e){
		logger.error(e.getMessage(), e);
		return R.error("没有权限，请联系管理员授权");
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
		List<ObjectError> errors = e.getBindingResult().getAllErrors();
		String tips = "参数不合法:";
		if (errors.size() > 0) {
			tips += errors.get(0).getDefaultMessage();
		}
		logger.error(e.getMessage(), e);
		return R.error(tips);
	}
	@ExceptionHandler(Exception.class)
	public R handleException(Exception e){
		logger.error(e.getMessage(), e);

		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);

		String msg = "";
		try
		{
			e.printStackTrace(pw);
			msg = sw.toString();
		} finally
		{
			pw.close();
		}
		msg = msg.replace("at ",",");
		String[] errorInfo = msg.split(",");
		StringBuffer sb = new StringBuffer();
		sb.append("<html>\n");
		sb.append("<body>\n");
		for (int i=0; i<errorInfo.length; i++){
			sb.append("<div>");
			if(i==0){
				sb.append(errorInfo[0]);
			}else{
				sb.append("&nbsp;&nbsp;&nbsp;&nbsp;"+errorInfo[i]);
			}
			sb.append("</div>");
		}
		mailService.sendSysErrorMail(sb.toString());
		return R.error("系统异常:"+e.getMessage());
	}
}
